package com.net.xpay.core.service.impl.api;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.net.common.util.HttpClientUtil;
import com.net.common.util.SerializationUtil;
import com.net.xpay.core.model.TaokeResponse;
import com.net.xpay.core.service.api.TaokedingdanApi;
import com.net.xpay.core.utils.EncodingUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpGet;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * 2020/2/12 19:40

 * 	state	Number	状态：1:淘客订单 0:非淘客订单 3:查询错误
 */
@Slf4j
@Service
public class TaokedingdanApiImpl implements TaokedingdanApi {

    private static final JsonParser JSON_PARSER = new JsonParser();

    private static final Integer SYSTEM_ERROR_STATE = 3;

    @Override
    public TaokeResponse getOrderState(String tid) {
        Preconditions.checkArgument(!Strings.isNullOrEmpty(tid));
        Map<String, String> params = new HashMap<>();
        params.put("apikey", "bvUUvzVQib");
        params.put("text", tid);

        String url = "https://api.taokouling.com/tkl/taokedingdan";
        url = url + "?";
        for (String key : params.keySet()) {
            String temp = key + "=" + EncodingUtil.getUrlEncodedString(params.get(key), "UTF-8") + "&";
            url = url + temp;
        }
        url = url.substring(0, url.length() - 1);

        String resp = null;
        try {
            HttpGet httpGet = HttpClientUtil.getGetRequest();
            httpGet.setURI(new URI(url));

            log.info("requestTaobaoKeOrder start|params={}", SerializationUtil.obj2String(params));
            resp = HttpClientUtil.getInstance().executeAndGet(httpGet, null, "UTF-8");
            log.info("requestTaobaoKeOrder end|params={}|resp={}", SerializationUtil.obj2String(params), resp);
            JsonObject jsonObject = JSON_PARSER.parse(resp).getAsJsonObject();
            Integer code = jsonObject.get("code").isJsonNull() ? null : jsonObject.get("code").getAsInt();
            if (code == null || code != 1) {
                log.warn("requestTaobaoKeOrder failed|params={}|resp={}", SerializationUtil.obj2String(params), resp);
                return TaokeResponse.getInstance(SYSTEM_ERROR_STATE, jsonObject.get("msg").isJsonNull() ? null : jsonObject.get("msg").getAsString());
            }

            Integer state = jsonObject.get("state").isJsonNull() ? null : jsonObject.get("state").getAsInt();
            String msg = jsonObject.get("msg").isJsonNull() ? null : jsonObject.get("msg").getAsString();

            return TaokeResponse.getInstance(state, msg);
        } catch (Exception e) {
            log.error("submitChahao error,params={},resp={}", SerializationUtil.obj2String(params), resp, e);
            return TaokeResponse.getInstance(SYSTEM_ERROR_STATE, "系统繁忙");
        }
    }
}
